package com.mk.cloud.common.service.core;

import act.apidoc.Description;
import com.alibaba.fastjson.JSON;
import com.mk.cloud.common.domain.GlArea;
import com.mk.cloud.common.interceptor.cookie.CookieService;
import org.apache.commons.lang3.StringUtils;
import org.osgl.mvc.annotation.GetAction;

import javax.inject.Inject;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class AreaService extends CookieService {

    @Inject
    private GlArea.Mapper glAreaMapper;

    @GetAction("/generateAreaFile.json")
    @Description("通用-地址选择-获取省份")
    public void generateAreaFile() {
        List<GlArea> allArea = glAreaMapper.all();

        List<GlArea> provinces = new ArrayList<>();

        for (int i = 0; i < allArea.size(); i++) {
            GlArea glArea = allArea.get(i);
            if (glArea.getPareacode().equals("000000")) {
                provinces.add(glArea);
            }
        }

        for (int i = 0; i < provinces.size(); i++) {
            GlArea province = provinces.get(i);

            List<GlArea> cities = new ArrayList<GlArea>();

            for (int j = 0; j < allArea.size(); j++) {
                GlArea glArea = allArea.get(j);
                if (StringUtils.equals(glArea.getPareacode(), province.getAreacode())) {
                    cities.add(glArea);
                }
            }

            province.setChildren(cities);
        }


        for (int i = 0; i < provinces.size(); i++) {
            GlArea province = provinces.get(i);
            List<GlArea> cities = province.getChildren();

            for (int k = 0; k < cities.size(); k++) {
                GlArea city = cities.get(k);
                List<GlArea> areas = new ArrayList<GlArea>();
                for (int j = 0; j < allArea.size(); j++) {
                    GlArea glArea = allArea.get(j);
                    if (StringUtils.equals(glArea.getPareacode(), city.getAreacode())) {
                        areas.add(glArea);
                    }
                }
                city.setChildren(areas);
            }
        }

        String fileName = "/Users/ianfung/Downloads/area.js";
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new FileWriter(fileName));
            out.write(JSON.toJSONString(provinces));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
